package com.hepinghospital.user.ui;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.hepinghospital.user.R;
import com.hepinghospital.user.base.BaseActivity;
import com.rest.constant.JDConstant;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import butterknife.BindView;
import jz.joyoung.robot.util.UtilString;

public class NewsActivity extends BaseActivity {
    @BindView(R.id.webview)
    WebView webview;
    @BindView(R.id.tv_title)
    TextView tvTitle;

    String url, helpContent, helpName;

    //字体颜色设为白色, “p”标签内的字体颜色  “*”定义了字体大小以及行高；
    public final static String CSS_STYLE = "<style>* {font-size:16px;line-height:20px;}p {color:#FFFFFF;}</style>";


    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void initViews() {

        WebSettings webSettings = webview.getSettings();
        webSettings.setUseWideViewPort(true);// 设置此属性，可任意比例缩放
        webSettings.setLoadWithOverviewMode(true); // 充满全屏幕
        webSettings.setBuiltInZoomControls(false);
        webSettings.setAppCacheEnabled(true);
        webSettings.setJavaScriptEnabled(true);
// 设置缓存模式
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);

// 开启 DOM storage API 功能
        webSettings.setDomStorageEnabled(true);
        webview.setVerticalScrollBarEnabled(false); //垂直不显示
        webview.setHorizontalScrollBarEnabled(false); // 水平不显示滚动条
        webview.setOverScrollMode(View.OVER_SCROLL_NEVER); // 禁止即在网页顶出现一个空白，又自动回去。

        webview.getSettings().setBlockNetworkImage(false); // 解决图片不显示
//如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        webview.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);

        webview.addJavascriptInterface(new AndroidToJs(), "android");
        webview.setWebChromeClient(new WebChromeClient());
        if (!UtilString.isEmpty(url)) {
            webview.loadUrl(url);
        } else if (!UtilString.isEmpty(helpContent)) {
            tvTitle.setText(helpName);
            //小类的富文本
            StringBuffer sbHtml = new StringBuffer();

//            sbHtml.append( "<html><head><meta http-equiv='content-type' content='text/html; charset=utf-8'>" );
//
//            sbHtml.append( "<meta charset='utf-8'  content='1'></head><body style='color: black;font-size: 45px !important;'><p></p >" );
            //添加文件的内容
            sbHtml.append(getHtmlData(helpContent));

            // webView.loadData(data, mimeType, encoding);

            //设置字符编码，避免乱码

            webview.getSettings().setDefaultTextEncodingName("utf-8");

            webview.loadDataWithBaseURL(null, sbHtml.toString(), "text/html", "utf-8", null);
        }
    }

    @Override
    protected void initData() {
        url = getIntent().getStringExtra("url");
        helpContent = getIntent().getStringExtra("helpContent");//富文本内容
        helpName = getIntent().getStringExtra("helpName");//帮助大类名字

    }

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_news;
    }

    class AndroidToJs {
        @JavascriptInterface
        public void jumpBrowser(String url) {
            Log.e("jsjson---", url);
            JSONObject jsonObject = JSONObject.parseObject(url);
            String type = jsonObject.getString("type");
            String path = jsonObject.getString("url");
            String appid = jsonObject.getString("appid");

            if ("miniApp".equals(type)) {
                IWXAPI api = WXAPIFactory.createWXAPI(NewsActivity.this, JDConstant.APP_ID);
                WXLaunchMiniProgram.Req req = new WXLaunchMiniProgram.Req();
                req.userName = appid; // 填小程序原始id
                req.path = path;                  ////拉起小程序页面的可带参路径，不填默认拉起小程序首页，对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"。
                req.miniprogramType = WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE;// 可选打开 开发版，体验版和正式版
                api.sendReq(req);
            } else if ("web".equals(type)) {
                Intent intent = new Intent();
                intent.setData(Uri.parse(path));//Url 就是你要打开的网址
                intent.setAction(Intent.ACTION_VIEW);
                startActivity(intent); //启动浏览器
            }
        }
    }

    /**
     * 富文本适配
     */
    private String getHtmlData(String bodyHTML) {
        String head = "<head>"
                + "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"> "
                + "<style>img{max-width: 100%; width:auto; height:auto;}</style>"
                + "</head>";
        return "<html>" + head + "<body>" + bodyHTML + "</body></html>";
    }
}
